package com.qf.job;

import com.qf.constant.CacheConstants;
import com.qf.constant.RabbitMQConstants;
import com.qf.feign.CacheFeign;
import com.qf.util.JavaMailUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.io.IOException;
import java.util.Set;

/**
 * @author yuan
 */
@Component
@Slf4j
public class MonitorQueueMessageJob implements SimpleJob {

    @Autowired
    private Channel channel;
    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private JavaMailUtil javaMailUtil;

    @Override
    public void execute(ShardingContext shardingContext) {

        //1.通过cache模块查询全部通道信息
        Set<String> keys = cacheFeign.keys(CacheConstants.CACHE_PREFIX_SMS_CHANNEL_ALL + "*");
        //2.遍历获取需要的通道ID
        for (String key : keys){
            String chanelID = key.substring(key.lastIndexOf(":")+1);
        //3.声明队列名称
            String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + chanelID;
            int messageCount = 0;
            try{
                //4.创建队列,并获取其中消息内容
                channel.queueDeclare(queueName,true,false,false,null);
                messageCount = channel.queueDeclarePassive(queueName).getMessageCount();
            }catch (IOException e){
                e.printStackTrace();
            }
            //5.判断消息数量
            if(messageCount > 5){
                log.info("[监控模块] {}队列中的消息,出现了消息堆积,消息的数量为：{}",queueName,messageCount);
                try{
                    javaMailUtil.sendMailForQueue(queueName,messageCount);
                }catch (MessagingException e){
                    e.printStackTrace();
                }
            }else {
                log.info("[监控模块] {}队列中的消息，没有出现堆积问题！",queueName);
            }

        }


    }

}
